require("dotenv").config();
const path = require("path");
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const makeNewProject = require("./newproject").makeNewProject;
const makeInviteorg = require("./inviteorg").makeInviteorg;
const confirmMsg = require("./confirmmsg").confirmMsg;
const addProjectDataset = require("./addprojectdataset").addProjectDataset;
const makeSignup = require("./signup").makeSignup;
const assigntask = require("./assigntask").assigntask;
const newAsyncTask = require("./newAsyncTask").sentDownloadMessage;
const newAiTask = require("./newAiTask").sentAiTaskMessage;
const weApp = require("./wechat").upload;
const weAppAiLib = require("./wechat/aiLib").upload;
const formidable = require("formidable");
const appid = "wx02bc18d5fde937ac";
const secret = "43d584139bbd524a794ea7bc5a85318b";
const request = require("request");

app.use(bodyParser.json());
app.use(express.static("upload")); //这个很重要，必须要这个才能拿到图片链接，而不是进入路由，有兴趣的同学可以删掉试验一下
app.post("/assigntask", async function(req, res) {
  try {
    var config;
    if (req.body.event) {
      config = req.body.event.data.new;
    } else {
      config = req.body;
    }
    var result = await assigntask(config);
    res.json(result);
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

app.post("/addprojectdataset", async function(req, res) {
  try {
    var dataset;
    if (req.body.event) {
      dataset = req.body.event.data.new;
    } else {
      dataset = req.body;
    }
    var result = await addProjectDataset(dataset);
    res.json(result);
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

app.post("/confirmmsg", async function(req, res) {
  try {
    var msg;
    if (req.body.event) {
      msg = req.body.event.data.new;
    } else {
      msg = req.body;
    }
    var result = await confirmMsg(msg);
    res.json(result);
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

app.post("/inviteorg", async function(req, res) {
  try {
    var orgMember;
    if (req.body.event) {
      orgMember = req.body.event.data.new;
    } else {
      orgMember = req.body;
    }
    var result = await makeInviteorg(orgMember);
    res.json(result);
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

app.post("/newproject", async function(req, res) {
  try {
    var project;
    if (req.body.event) {
      project = req.body.event.data.new;
    } else {
      project = req.body;
    }
    var result = await makeNewProject(project);
    res.json(result);
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

app.post("/signup", async function(req, res) {
  try {
    var signup;
    if (req.body.event) {
      signup = req.body.event.data.new;
    } else {
      signup = req.body;
    }
    var result = await makeSignup(signup);
    res.json(result);
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

app.post("/newAsyncTask", async function(req, res) {
  try {
    var signup;
    if (req.body.event) {
      signup = req.body.event.data.new;
    } else {
      signup = req.body;
    }
    var result = await newAsyncTask(signup);
    res.json(result);
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

app.post("/newAiTask", async function(req, res) {
  console.log("newAiTask");
  try {
    var signup;
    if (req.body.event) {
      signup = req.body.event.data.new;
    } else {
      signup = req.body;
    }
    var result = await newAiTask(signup);
    res.json(result);
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

app.post("/wechatUpload", async function(req, res) {
  try {
    var form = new formidable.IncomingForm();
    let uploadDir = path.join(__dirname, "./upload/");
    form.uploadDir = uploadDir; //本地文件夹目录路径
    //    form.parse(req, (err, fields, files) => {
    form.parse(req, async (err, fields, files) => {
      var result = await weApp(fields, files);
      console.log(result);
      res.json(result);
    });
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

function getSessionKey(url) {
  return new Promise((resolve, reject) => {
    request({ url }, function(error, response, body) {
      if (error) {
        reject(error);
      }
      console.log(error, body);
      resolve(body);
    });
  });
}

app.get("/wechatGetId", async function(req, res) {
  try {
    var l =
      "https://api.weixin.qq.com/sns/jscode2session?appid=" +
      appid +
      "&secret=" +
      secret +
      "&js_code=" +
      req.query.code +
      "&grant_type=authorization_code";
    const session_key = await getSessionKey(l);
    res.send(session_key);
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

app.post("/wechatAiLib", async function(req, res) {
  try {
    var form = new formidable.IncomingForm();
    let uploadDir = path.join(__dirname, "./upload/");
    form.uploadDir = uploadDir; //本地文件夹目录路径
    //    form.parse(req, (err, fields, files) => {
    form.parse(req, async (err, fields, files) => {
      var result = await weAppAiLib(fields, files);
      console.log(result);
      res.json(result);
    });
  } catch (e) {
    console.log(e);
    res.status(500).json(e.toString());
  }
});

var server = app.listen(4000, function() {
  console.log("server listening on port 4000");
});
